package com.chushouya.order.service.admin.impl;

import com.chushouya.order.dto.admin.action.*;
import com.general.framework.core.lang.Jsons;
import com.chushouya.order.constants.OrderActionEnum;
import com.chushouya.order.constants.OrderPayTypeEnum;
import com.chushouya.order.constants.OrderStatusEnum;
import com.chushouya.order.dao.entity.OrderEntity;
import com.chushouya.order.dao.entity.OrderProductEntity;
import com.chushouya.order.dao.repository.OrderProductRepository;
import com.chushouya.order.dao.repository.OrderRepository;
//=====order.dto.admin.action.*;
import com.chushouya.order.dto.admin.action.*;
import com.chushouya.order.service.admin.AlipayOrderPayService;
import com.chushouya.order.service.admin.KefuOrderActionCtrlService;
import com.chushouya.order.service.admin.KefuOrderActionService;
import com.chushouya.order.service.common.CommonOrderActionService;
import com.general.framework.core.exception.Ex;
import com.general.framework.core.lang.Strings;
import com.chushouya.order.service.common.OrderLogService;
import com.chushouya.order.service.common.OrderPaymentService;
import com.chushouya.manager.service.common.UserPaymentMethodApiService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.Objects;

@Service
@Slf4j
public class KefuOrderActionServiceImpl implements KefuOrderActionService {

    @Resource
    private CommonOrderActionService commonOrderActionService;

    @Resource
    private KefuOrderActionCtrlService kefuOrderActionCtrlService;

    @Resource
    private OrderLogService orderLogService;

    @Resource
    private OrderRepository orderRepository;

    @Resource
    private OrderProductRepository orderProductRepository;

    @Resource
    private AlipayOrderPayService alipayOrderPayService;

    @Resource
    private UserPaymentMethodApiService userPaymentMethodApiService;

    @Resource
    private OrderPaymentService orderPaymentService;




    private OrderEntity getOrder(Long orderId) {
        OrderEntity orderEntity = orderRepository.selectByPrimaryKey(orderId);
        if (orderEntity == null) {
            throw Ex.business("订单不存在");
        }
        return orderEntity;
    }

    /**
     * 获取订单产品信息
     * @param orderId
     * @return
     */
    private OrderProductEntity getOrderProduct(Long orderId) {
        OrderProductEntity orderProductEntity = orderProductRepository.selectByOrderId(orderId);
        if(Objects.isNull(orderProductEntity)){
            throw Ex.business("订单产品不存在");
        }
        return orderProductEntity;
    }

    /**
     * 跟进订单
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void waitOrder(OrderWaitAction dto) {
        final OrderEntity orderEntity = this.getOrder(dto.getOrderId());
        this.kefuOrderActionCtrlService.actionExecuteCheck(dto.getOrderAction(), orderEntity);

        commonOrderActionService.waitOrder(orderEntity, dto.getActionNote());
    }

    /**
     * 关闭订单
     */
    @Override
//    @Transactional(rollbackFor = Exception.class)
    public void closeOrder(OrderCloseAction close) {
        final OrderEntity orderEntity = this.getOrder(close.getOrderId());
        this.kefuOrderActionCtrlService.actionExecuteCheck(close.getOrderAction(), orderEntity);

        commonOrderActionService.closeOrder(orderEntity, Strings.format("{} {}", close.getOrderAction().getActionName(), close.getActionNote()), close.getOrderAction().toOrderStatus().value());
    }

    /**
     * 快递已发货
     *
     * @param orderStatusDTO
     */
    @Override
    public void deliveryOrder(OrderDeliveryAction orderStatusDTO) {
        final OrderEntity orderEntity = this.getOrder(orderStatusDTO.getOrderId());
        this.kefuOrderActionCtrlService.actionExecuteCheck(orderStatusDTO.getOrderAction(), orderEntity);

        commonOrderActionService.deliveryOrder(orderEntity, Strings.format("{} {}", orderStatusDTO.getOrderAction().getActionName(), orderStatusDTO.getActionNote()), orderStatusDTO.getOrderAction().toOrderStatus().value());
    }

    /**
     * 订单收货
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void orderReceive(OrderReceiveAction receive) {
        final OrderEntity orderEntity = this.getOrder(receive.getOrderId());
        this.kefuOrderActionCtrlService.actionExecuteCheck(receive.getOrderAction(), orderEntity);

        commonOrderActionService.receiveOrder(orderEntity, Strings.format("订单已签收,等待质检 {}", Strings.defaultString(receive.getActionNote(), "")), receive.getOrderAction().toOrderStatus().value());
    }

    /**
     * 订单退回
     */
    @Override
    public void orderReturn(OrderReturnAction orderStatusDTO) {
        log.info("订单退回：{}", orderStatusDTO);
        final OrderEntity orderEntity = this.getOrder(orderStatusDTO.getOrderId());
        this.kefuOrderActionCtrlService.actionExecuteCheck(orderStatusDTO.getOrderAction(), orderEntity);

        commonOrderActionService.returnOrder(orderEntity, Strings.format("{} {}", orderStatusDTO.getOrderAction().getActionName(), orderStatusDTO.getActionNote()), orderStatusDTO.getOrderAction().toOrderStatus().value());
    }

    /**
     * 派单
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void orderDispatch(OrderDispatchAction dispatch) {
        final OrderEntity orderEntity = this.getOrder(dispatch.getOrderId());
        this.kefuOrderActionCtrlService.actionExecuteCheck(dispatch.getOrderAction(), orderEntity);

        commonOrderActionService.dispatchOrder(orderEntity, dispatch.getClerkId(), dispatch.getActionNote(), dispatch.getOrderAction().toOrderStatus().value());
    }

    /**
     * 议价
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void orderBargain(OrderBargainAction bargain) {
        final OrderEntity orderEntity = this.getOrder(bargain.getOrderId());
        this.kefuOrderActionCtrlService.actionExecuteCheck(bargain.getOrderAction(), orderEntity);

        commonOrderActionService.bargainOrder(orderEntity, bargain.getCompletePrice(), Strings.format("{},成交价为:{}元 {}", bargain.getOrderAction().getActionName(), bargain.getCompletePrice(), bargain.getActionNote()), bargain.getOrderAction().toOrderStatus().value());

    }

    /**
     * 重新议价
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void orderReBargain(OrderReBargainAction reBargain) {
        final OrderEntity orderEntity = this.getOrder(reBargain.getOrderId());
        this.kefuOrderActionCtrlService.actionExecuteCheck(reBargain.getOrderAction(), orderEntity);

        commonOrderActionService.reBargainOrder(orderEntity, Strings.format("{} {}", reBargain.getOrderAction().getActionName(), reBargain.getActionNote()), reBargain.getOrderAction().toOrderStatus().value());

    }

    /**
     * 重新下单
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Long orderAgain(OrderAgainAction dto) {
        return null;
//        return orderCopyService.orderCopy(dto.getOrderId());
    }

    /**
     * 完成订单
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void orderComplete(OrderCompleteAction complete) {
        final OrderEntity orderEntity = this.getOrder(complete.getOrderId());
        this.kefuOrderActionCtrlService.actionExecuteCheck(complete.getOrderAction(), orderEntity);
        final BigDecimal completePrice = orderEntity.getCompletePrice();


        final String remark = Strings.format("{},订单金额:{}元,支付方式:{} {}", complete.getOrderAction().getActionName(), completePrice, OrderPayTypeEnum.getDesc(complete.getPayType()), complete.getActionNote());
        commonOrderActionService.completeOrder(orderEntity, complete.getPayType(), completePrice, remark, complete.getOrderAction().toOrderStatus().value());

    }

    @Override
    public void resetOrderStatus(ResetOrderStatusAction dto) {
        final OrderEntity orderEntity = this.getOrder(dto.getOrderId());
        this.kefuOrderActionCtrlService.actionExecuteCheck(dto.getOrderAction(), orderEntity);
        commonOrderActionService.resetOrder(orderEntity,"", OrderStatusEnum.WAIT_CHECK.value());
    }

    /**
     * 预约快递
     */

    @Override
    public void orderDeliver(OrderDeliverAction dto) {
        final OrderEntity orderEntity = this.getOrder(dto.getOrderId());
        this.kefuOrderActionCtrlService.actionExecuteCheck(dto.getOrderAction(), orderEntity);

        final String msg = Strings.format("预约快递发货 {}", Strings.defaultString(dto.getActionNote(), ""));
        commonOrderActionService.deliverOrder(orderEntity, msg, dto.getOrderAction().toOrderStatus().value());



    }

    @Override
    public void closeOrderTimeout(OrderTimeoutAction dto) {

    }

    @Override
    public void clerkSaleOut(OrderClerkSaleOutAction dto) {


    }

    @Override
    public void orderSendEnergy(OrderSendEnergyAction dto) {
        final OrderEntity orderEntity = this.getOrder(dto.getOrderId());
        this.kefuOrderActionCtrlService.actionExecuteCheck(dto.getOrderAction(), orderEntity);
        final String remark = Strings.format("重新发送能量 {}",Strings.defaultString(dto.getActionNote(), ""));
        commonOrderActionService.sendEnergy(orderEntity, remark);
    }

    @Override
    public void orderQuality(OrderQualityAction dto) {
        final OrderEntity orderEntity = this.getOrder(dto.getOrderId());
        this.kefuOrderActionCtrlService.actionExecuteCheck(dto.getOrderAction(), orderEntity);

        // 更新订单产品的质检项
        OrderProductEntity orderProductEntity = getOrderProduct(orderEntity.getOrderId());
        OrderProductEntity orderProductUpdate = new OrderProductEntity();
        orderProductUpdate.setOrderId(orderEntity.getOrderId());
        orderProductUpdate.setMeid(dto.getMeid());
        orderProductUpdate.setQualityRemark(dto.getActionNote());
        orderProductUpdate.setQualityItem(Jsons.toJsonString(dto.getQualityOption()));
        orderProductUpdate.setQualityPrice(dto.getQualityPrice());
        orderProductUpdate.setOrderProductId(orderProductEntity.getOrderProductId());
        orderProductRepository.updateByPrimaryKeySelective(orderProductUpdate);

        //插入订单操作记录
        final String remark = Strings.format("订单质检 {} 质检价：{}元",Strings.defaultString(dto.getActionNote(), ""), dto.getQualityPrice());
        orderLogService.addOrderActionLog(orderEntity.getOrderId(), OrderActionEnum.QUALITY_ORDER.value(), remark);

        commonOrderActionService.qualityOrder(orderEntity,remark, dto.getOrderAction().toOrderStatus().value(), dto.getQualityPrice());
    }

    @Override
//    @Transactional(rollbackFor = Exception.class)
    public void orderCompletePay(OrderCompletePayAction dto) {
        final OrderEntity orderEntity = this.getOrder(dto.getOrderId());
        this.kefuOrderActionCtrlService.actionExecuteCheck(dto.getOrderAction(), orderEntity);

        // 使用公共支付服务执行支付流程
        orderPaymentService.executeOrderPayment(orderEntity);
    }


}
